from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkalidns.request.v20150109.DescribeSubDomainRecordsRequest import DescribeSubDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
import requests
import json
import configparser
import os

'''配置文件'''
conf = configparser.ConfigParser()
root_path = os.path.dirname(os.path.abspath(__file__))

'''读取配置文件'''
def readConf(group,key):
    #配置文件路徑
    conf.read(root_path + '/app.conf')
    # print(conf)
    data = conf.get(group, key)
    if(key == 'SLD'):
        #SLD是數組配置
        data = eval(data)

    return data

'''連接阿里雲'''
client = AcsClient(readConf('aliyun','accessKeyId'), readConf('aliyun','accessSecret'), 'cn-hangzhou')

'''獲取當前ip地址'''
def getIp(type):
    session = requests.Session()
    session.trust_env = False
    if (type == 'v4'):
        response = session.get('https://v4.ident.me/').text
    else:
        response = session.get('https://v6.ident.me/').text
    print("获取到IP地址：%s" % response)
    return response

'''修改域名ddns的方法'''
def update(RecordId, RR, Type, Value):
    from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
    request = UpdateDomainRecordRequest()
    request.set_accept_format('json')
    request.set_RecordId(RecordId)
    request.set_RR(RR)
    request.set_Type(Type)
    request.set_Value(Value)
    response = client.do_action_with_exception(request)

'''添加新的ddns的方法'''
def add(DomainName, RR, Type, Value):
    from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import AddDomainRecordRequest
    request = AddDomainRecordRequest()
    request.set_accept_format('json')
    request.set_DomainName(DomainName)
    request.set_RR(RR)
    request.set_Type(Type)
    request.set_Value(Value)
    response = client.do_action_with_exception(request)

'''獲取域名ddns的記錄'''
def getList(DomainName,RR):
    request = DescribeSubDomainRecordsRequest()
    request.set_accept_format('json')
    request.set_DomainName(DomainName)
    request.set_SubDomain(RR + '.' + DomainName)
    response = client.do_action_with_exception(request)
    # domain_list = json.loads(response)
    return response;

'''ipv4-ddns的主函數'''
def ipv4Main():
    DomainName = readConf('aliyun', 'domain')
    SLD = readConf('ipv4','SLD')
    ipv4 = getIp('v4')
    for once in SLD:
        domain_list = json.loads(getList(DomainName,once))
        if domain_list['TotalCount'] == 0:
            add(DomainName, once, "A", ipv4)
            print("新建域名解析成功")
        elif domain_list['TotalCount'] == 1:
            if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv4.strip():
                update(domain_list['DomainRecords']['Record'][0]['RecordId'], once, "A", ipv4)
                print("修改域名解析成功")
            else:
                print("IPv4地址沒有改變")
        else:
            print('IPv4未知錯誤')

'''ipv6-ddns的主函數'''
def ipv6Main():
    DomainName = readConf('aliyun', 'domain')
    SLD = readConf('ipv6', 'SLD')
    ipv6 = getIp('v6')
    for once in SLD:
        domain_list = json.loads(getList(DomainName, once))
        if domain_list['TotalCount'] == 0:
            add(DomainName, once, "AAAA", ipv6)
            print("新建域名解析成功")
        elif domain_list['TotalCount'] == 1:
            if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv6.strip():
                update(domain_list['DomainRecords']['Record'][0]['RecordId'], once, "AAAA", ipv6)
                print("修改域名解析成功")
            else:
                print("IPv6地址沒有改變")
        else:
            print('IPv6未知錯誤')

if __name__ == '__main__':
    ipv6Flag = readConf('ipv6','flag')
    ipv4Flag = readConf('ipv4','flag')

    try:
        if (ipv4Flag == 'true'):
            ipv4Main()

        if (ipv6Flag == 'true'):
            ipv6Main()
    except Exception as r:
        print('獲取IP未知错误 %s' % (r))
        os._exit(0)

